package com.thqmcp.server.service.impl;

import com.thqmcp.server.model.McpError;
import com.thqmcp.server.model.McpMessage;
import com.thqmcp.server.model.McpTool;
import com.thqmcp.server.service.McpService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * MCP服务实现类
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class McpServiceImpl implements McpService {

    @Override
    public McpMessage getServerInfo() {
        Map<String, Object> serverInfo = new HashMap<>();
        serverInfo.put("name", "THQMCP Server");
        serverInfo.put("version", "1.0.0");
        serverInfo.put("description", "基于Spring Boot和Spring AI的MCP服务器");
        serverInfo.put("capabilities", Arrays.asList("tools", "resources", "prompts"));

        McpMessage response = new McpMessage();
        response.setJsonrpc("2.0");
        response.setType("response");
        response.setResult(serverInfo);
        
        return response;
    }

    @Override
    public List<McpTool> getAvailableTools() {
        List<McpTool> tools = new ArrayList<>();
        
        // 示例工具1：计算器
        McpTool calculator = McpTool.builder()
                .name("calculator")
                .description("执行基本数学计算")
                .inputSchema(createCalculatorSchema())
                .build();
        tools.add(calculator);
        
        // 示例工具2：文本处理
        McpTool textProcessor = McpTool.builder()
                .name("text_processor")
                .description("处理和分析文本内容")
                .inputSchema(createTextProcessorSchema())
                .build();
        tools.add(textProcessor);
        
        return tools;
    }

    @Override
    public McpMessage callTool(McpMessage request) {
        McpMessage response = new McpMessage();
        response.setJsonrpc("2.0");
        response.setType("response");
        response.setId(request.getId());
        
        try {
            String method = request.getMethod();
            Object params = request.getParams();
            
            Object result = switch (method) {
                case "calculator" -> handleCalculator(params);
                case "text_processor" -> handleTextProcessor(params);
                default -> throw new IllegalArgumentException("未知的工具: " + method);
            };
            
            response.setResult(result);
            
        } catch (Exception e) {
            log.error("工具调用失败", e);
            McpError error = new McpError(-32000, "工具调用失败: " + e.getMessage(), null);
            response.setError(error);
        }
        
        return response;
    }

    @Override
    public McpMessage handleMessage(McpMessage message) {
        McpMessage response = new McpMessage();
        response.setJsonrpc("2.0");
        response.setType("response");
        response.setId(message.getId());
        
        try {
            String method = message.getMethod();
            
            Object result = switch (method) {
                case "initialize" -> handleInitialize(message.getParams());
                case "tools/list" -> getAvailableTools();
                case "tools/call" -> callTool(message);
                default -> throw new IllegalArgumentException("不支持的方法: " + method);
            };
            
            response.setResult(result);
            
        } catch (Exception e) {
            log.error("消息处理失败", e);
            McpError error = new McpError(-32601, "方法未找到: " + e.getMessage(), null);
            response.setError(error);
        }
        
        return response;
    }

    private Map<String, Object> createCalculatorSchema() {
        Map<String, Object> schema = new HashMap<>();
        schema.put("type", "object");
        
        Map<String, Object> properties = new HashMap<>();
        
        Map<String, Object> expression = new HashMap<>();
        expression.put("type", "string");
        expression.put("description", "要计算的数学表达式");
        properties.put("expression", expression);
        
        schema.put("properties", properties);
        schema.put("required", Arrays.asList("expression"));
        
        return schema;
    }

    private Map<String, Object> createTextProcessorSchema() {
        Map<String, Object> schema = new HashMap<>();
        schema.put("type", "object");
        
        Map<String, Object> properties = new HashMap<>();
        
        Map<String, Object> text = new HashMap<>();
        text.put("type", "string");
        text.put("description", "要处理的文本内容");
        properties.put("text", text);
        
        Map<String, Object> operation = new HashMap<>();
        operation.put("type", "string");
        operation.put("enum", Arrays.asList("length", "uppercase", "lowercase", "reverse"));
        operation.put("description", "要执行的操作");
        properties.put("operation", operation);
        
        schema.put("properties", properties);
        schema.put("required", Arrays.asList("text", "operation"));
        
        return schema;
    }

    private Object handleCalculator(Object params) {
        // 简单的计算器实现
        Map<String, Object> result = new HashMap<>();
        result.put("result", "计算功能暂未实现");
        return result;
    }

    private Object handleTextProcessor(Object params) {
        // 简单的文本处理实现
        Map<String, Object> result = new HashMap<>();
        result.put("result", "文本处理功能暂未实现");
        return result;
    }

    private Object handleInitialize(Object params) {
        Map<String, Object> capabilities = new HashMap<>();
        capabilities.put("tools", true);
        capabilities.put("resources", false);
        capabilities.put("prompts", false);
        
        Map<String, Object> result = new HashMap<>();
        result.put("protocolVersion", "1.0.0");
        result.put("capabilities", capabilities);
        result.put("serverInfo", Map.of("name", "THQMCP Server", "version", "1.0.0"));
        
        return result;
    }
} 